package com.bootdo.clouddo.controller.book;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bootdo.clouddo.domain.book.BookDetail;
import com.bootdo.clouddo.redis.CommonRedisService;
import com.bootdo.clouddo.redis.RedisEnum;
import com.bootdo.clouddo.service.book.IBookDetailService;
import com.bootdo.clouddo.task.BookTask;
import com.bootdo.clouddo.utils.StringUtils;
import com.bootdo.clouddo.utils.book.BookApi;
import com.bootdo.clouddo.utils.book.BookUtils;
import com.bootdo.clouddo.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.print.Book;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/book/v1")
public class MainController {

    @Autowired
    private CommonRedisService redisService;

    @Autowired
    private BookTask bookTask;

    @Autowired
    private IBookDetailService bookDetailService;

    @GetMapping("/detail")
    public R getDetail(String id) {
        try {
            // redis查询
            Optional<BookDetail> op = redisService.getAsOptional(RedisEnum.BOOK_DETAIL.getKey() + id);
            if(op.isPresent()) {
                return R.data(op.get());
            }
            // mysql查询
            BookDetail bookDetail = bookDetailService.findById(Long.parseLong(id));
            if(bookDetail != null) {
                return R.data(bookDetail);
            }
            // 远程查询
            JSONObject resultVo = BookUtils.fetchJSONObject(BookApi.DETAIL.getUrl() + id);
            if(resultVo != null) {
                // 保存
                bookTask.saveDetail(resultVo);
                // 返回数据
                return R.data(resultVo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error();
    }

    @GetMapping("/menu")
    public R getMenu(Long bookId, Integer siteId) {
        try {
            siteId = (siteId == 10) ? 36: siteId;
            Optional<JSONObject> op = redisService.getAsOptional(RedisEnum.BOOK_CATALOGUE.getKey() + bookId + "_" + siteId);
            if(op.isPresent()) {
                // 保存
                bookTask.saveCatalogue(op.get(), bookId, siteId);
                return R.data(op.get());
            }
            Map param = new HashMap();
            param.put("bookId", bookId);
            param.put("siteId", siteId);
            JSONObject resultVo = BookUtils.fetchJSONObject(BookApi.MENU.getUrl(), param);
            if(resultVo == null) {
                System.out.println("load menu err, from site: " + siteId);
                for (int i = 2; i < 100; i++) {
                    System.out.println("load menu from site: " + i);
                    if(i == 10) {continue;}
                    param.put("siteId", i);
                    resultVo = BookUtils.fetchJSONObject(BookApi.MENU.getUrl(), param);
                    if(resultVo != null && resultVo.size() > 0) {
                        // 获取第一章，获取失败就不采用该site
                        String chapter = resultVo.getString("chapter");
                        JSONArray list = resultVo.getJSONArray("list");
                        if(StringUtils.isBlank(chapter) || list == null || list.isEmpty()) {
                            continue;
                        }
                        if(StringUtils.isEmpty(BookUtils.getContent(chapter.replace("[chapterid]", list.getJSONObject(0).getString("url")), i))) {
                            continue;
                        }
                        // 获取成功。继续
                        siteId = i;
                        bookDetailService.updateSiteId(bookId, i);
                        break;
                    }
                }
            }
            if(resultVo != null) {
                // 保存
                bookTask.saveCatalogue(resultVo, bookId, siteId);
                return R.data(resultVo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error();
    }

    @GetMapping("/friend/read")
    public R getFriendRead(String cateId) {
        try {
            JSONArray resultVo = BookUtils.fetchJSONArray(BookApi.FRIEND_READ.getUrl() + cateId);
            if(resultVo != null) {
                // 保存
                bookTask.saveDetailArr(resultVo);
                // 返回数据
                return R.data(resultVo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error();
    }
}
